#coding:utf-8

import time

import logging.config
from logging import getLogger

from event import DelayEvent
from eventloop import EventLoop


class App(object):

    def __init__(self):
        self.logger = getLogger("App")

    def memFunc1(self):
        s = 10
        x = 20
        i = s+x
        logger = getLogger("memfunc1")
        logger.debug("some message 1")

    def memFunc2(self):
        s = 10
        x = 20
        i = x - s
        logger = getLogger("memfunc2")
        logger.debug("some message 2")

    def run(self):
        self.evtloop = EventLoop()

        test_number = 2
        for i in xrange(test_number):
            evt1 = DelayEvent(self.memFunc1, (), 2,)
            self.evtloop.postEvent(evt1)

        for j in xrange(test_number):
            evt2 = DelayEvent(self.memFunc2, (), 3,)
            self.evtloop.postEvent(evt2)

        try:
            self.evtloop.loop()
        except Exception:
            import traceback
            self.logger.error(traceback.format_exc())


def cfgLogging():
    cfgdict = {
               'version': 1,
               'disable_existing_loggers': False,
               'formatters': {
                              'standard': {
                                           'format':
    '%(asctime)s,%(msecs)03d [%(process)d] [%(levelname)s] %(name)s: %(message)s',
    'datefmt': '%Y-%m-%d %H:%M:%S'
                                                      },
                              },
               'handlers': {
                            'default': {
                                        'level':'DEBUG',
                                        'class':'logging.StreamHandler',
                                        'stream': 'ext://sys.stderr',
                                        'level': 'DEBUG',
                                        'formatter': 'standard',
                                        },
                            },
               'loggers': {
                           '': {
                                'handlers': ['default'],
                                'level': 'DEBUG',
                                'propagate': True
                                },
                           },
               }

    logging.config.dictConfig(cfgdict)


def main():
#    import cProfile

    cfgLogging()
    app = App()
    app.run()
#    func = app.run
#    cProfile.run(  'func()', 'runstat.prof')


if __name__ == '__main__':
    main()
